<template>
  <!--标签页以上-->
  <div class="mt-[100px]">
    <nut-row class="body">
      <!--标签页-登录/忘记密码-->
      <nut-col :span="24">
        <nut-tabs v-model="tabschange" background="#ffffff">
          <nut-tab-pane :title="changecode ? '登录' : '忘记密码'" pane-key="1">
            <!--登录表单-->
            <nut-form v-if="changecode" ref="formRef1" :model-value="formloadData" :rules="rulues">
              <nut-form-item label="账户:" prop="phone" :required="false">
                <nut-input
                  v-model="formloadData.phone"
                  placeholder="请输入手机号"
                  type="text"
                  @blur="customBlurValidate('phone')"
                  max-length="50"
                  @keydown="handle"
                  class="rounded"
                />
              </nut-form-item>
              <nut-form-item label="密码:" prop="password" :required="false">
                <nut-input
                  v-model="formloadData.password"
                  placeholder="请输入密码"
                  type="password"
                  password="true"
                  @blur="customBlurValidate('password')"
                  max-length="50"
                  @keydown="handle"
                  class="rounded"
                />
              </nut-form-item>
              <nut-form-item label="人员" prop="type" :required="false">
                <nut-radio-group v-model="formloadData.type" direction="horizontal" class="flex gap-4">
                  <nut-radio label="customer">用户</nut-radio>
                  <nut-radio label="service">服务人员</nut-radio>
                </nut-radio-group>
              </nut-form-item>
              <nut-form-item body-align="center">
                <nut-button type="primary" @click="loading" class="rounded-lg px-8">登录</nut-button>
              </nut-form-item>
            </nut-form>
          </nut-tab-pane>
          <!--标签页-注册-->
          <nut-tab-pane title="注册" pane-key="2">
            <nut-form ref="formRef2" :model-value="formregisterData" :rules="rulues">
              <nut-form-item label="手机号 :" prop="phone" :required="false">
                <nut-input
                  v-model="formregisterData.phone"
                  placeholder="请输入手机号"
                  type="number"
                  @blur="customBlurValidate('phone')"
                  max-length="11"
                  class="rounded"
                />
              </nut-form-item>

              <nut-form-item label="用户名" prop="username" :required="false">
                <nut-input
                  v-model="formregisterData.username"
                  placeholder="请输入用户名"
                  type="text"
                  @blur="customBlurValidate('username')"
                  max-length="50"
                  class="rounded"
                />
              </nut-form-item>
              <nut-form-item label="email" prop="email" :required="false">
                <nut-input
                  v-model="formregisterData.email"
                  placeholder="请输入邮箱"
                  type="text"
                  @blur="customBlurValidate('email')"
                  max-length="50"
                  class="rounded"
                />
              </nut-form-item>
              <nut-form-item label="密码" prop="password" :required="false">
                <nut-input
                  v-model="formregisterData.password"
                  placeholder="请输入密码"
                  type="password"
                  password="true"
                  @blur="customBlurValidate('password')"
                  max-length="50"
                  class="rounded"
                />
              </nut-form-item>
              <!-- 只有微信小程序端内置了省市区数据 -->
              <!-- #ifdef MP-WEIXIN -->
              <nut-form-item label="城市" prop="address" :required="false">
                <picker
                  @change="onFullLocationChange"
                  mode="region"
                  class="flex-1"
                  :value="formregisterData?.address?.split(' ')"
                >
                  <view v-if="formregisterData?.address" class="text-gray-800">{{ formregisterData.address }}</view>
                  <view class="text-gray-500" v-else>请选择城市</view>
                </picker>
              </nut-form-item>
              <!-- #endif -->
              <nut-form-item body-align="center">
                <nut-button type="primary" @click="register" class="rounded-lg px-8">注册</nut-button>
              </nut-form-item>
            </nut-form>
          </nut-tab-pane>
        </nut-tabs>
      </nut-col>
    </nut-row>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import { useUserStore } from "@/store/modules/user";
//忘记密码
const changecode = ref(true);

//表单数据
const formloadData = reactive({
  phone: "",
  password: "",
  type: "customer",
});
const formregisterData = ref({
  username: "",
  password: "",
  phone: "",
  email: "",
  address: "",
});

//清空方法
const clearformloadData = () => {
  (formloadData.phone = ""), (formloadData.password = "");
};
const clearformregisterData = () => {
  (formregisterData.value.password = ""),
    (formregisterData.value.phone = ""),
    (formregisterData.value.username = ""),
    (formregisterData.value.email = ""),
    (formregisterData.value.address = "");
};

//表单验证
const formRef1 = ref<any>();
const formRef2 = ref<any>();
const formRef3 = ref<any>();
//初始化仓库
const userStore = useUserStore();

//禁用tab
const handle = (e: KeyboardEvent) => {
  if (e.key === "Tab") {
    e.preventDefault();
  }
};
//修改城市;
let fullLocationCode: [string, string, string] = ["", "", ""];
const onFullLocationChange: UniHelper.RegionPickerOnChange = (ev) => {
  // 修改前端界面
  formregisterData.value.address = ev.detail.value.join(" ");
  // 提交后端更新
  fullLocationCode = ev.detail.code!;
};
//登录
const loading = () => {
  formRef1.value?.validate().then(async ({ valid }: any) => {
    if (valid) {
      try {
        const data = await userStore.getloadingdata(formloadData);
        if (data.code == 200) {
          // 先更新用户类型
          await userStore.updatetype(formloadData.type);
          // 再设置用户信息
          userStore.setUserInfo(data.data.id, data.data.username);

          // 确保数据已经存储到本地
          await new Promise((resolve) => {
            setTimeout(() => {
              // 验证数据是否已经存储
              const storedType = uni.getStorageSync("usertype");
              const storedUserId = uni.getStorageSync("userId");
              const storedUsername = uni.getStorageSync("username");

              if (storedType && storedUserId && storedUsername) {
                uni.showToast({
                  title: "登录成功",
                });
                clearformloadData();
                uni.reLaunch({
                  url: "/pages/modules/user/home/index",
                });
                resolve(true);
              } else {
                uni.showToast({
                  title: "数据存储失败，请重试",
                  icon: "none",
                });
              }
            }, 1000);
          });
        } else if (data.code == 500) {
          uni.showToast({
            title: data.msg,
            icon: "none",
          });
        } else {
          uni.showToast({
            title: "操作失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error(error);
      }
    }
  });
};
//注册
const tabschange = ref<string>("1");

const register = () => {
  formRef2.value?.validate().then(({ valid }: any) => {
    if (valid) {
      // 更新store中的formregisterData的每个属性
      Object.assign(userStore.formregisterData, formregisterData.value);

      userStore.getregisterdata().then((data: any) => {
        if (data.code == 200) {
          uni.showToast({
            title: "注册成功",
          });
          tabschange.value = "1";
          formloadData.phone = formregisterData.value.phone;
          formloadData.password = formregisterData.value.password;
          clearformregisterData();
          changecode.value = true;
        }
      });
    }
  });
};
//失焦校验
const customBlurValidate = (prop: any) => {
  if (tabschange.value == "1") {
    formRef1.value?.validate(prop).then(({ valid }: any) => {
      if (valid) {
      }
    });
    formRef3.value?.validate(prop).then(({ valid }: any) => {
      if (valid) {
      }
    });
  } else {
    formRef2.value?.validate(prop).then(({ valid }: any) => {
      if (valid) {
      }
    });
  }
};
// Promise 异步校验
const asyncValidator = (val: any) => {
  const telReg = /^400(-?)[0-9]{7}$|^1\d{10}$|^0[0-9]{2,3}-[0-9]{7,8}$/;
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (!val) {
        reject("请输入手机号");
      } else if (!telReg.test(val)) {
        reject("手机号格式不正确");
      } else {
        resolve("");
      }
    }, 300);
  });
};
//表单基本校验
const rulues = {
  phone: [{ validator: asyncValidator, message: "请输入手机号" }],
  username: [
    { required: true, message: "用户名不能为空" },
    { regex: /^[^\s]+$/, message: "用户名不能输入空格" },
  ],
  email: [
    { required: true, message: "邮箱不能为空" },
    { regex: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: "邮箱格式不正确" },
  ],
  password: [
    { required: true, message: "密码不能为空" },
    { regex: /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+$/, message: "只能输入英文、数字、特殊字符" },
  ],
  type: [{ required: true, message: "请选择人员类型" }],
  address: [{ required: true, message: "请选择城市" }],
};
</script>
<style lang="scss" scoped></style>
